package com.runen.infinitemovement.cardview;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.cardview.widget.CardView;
import androidx.viewpager.widget.PagerAdapter;

import com.runen.infinitemovement.R;
import com.runen.infinitemovement.model.entity.SportsStopEntity;
import com.runen.infinitemovement.tool.GlideUtils;

import java.util.ArrayList;
import java.util.List;

public class CardPagerAdapter extends PagerAdapter implements CardAdapter {

    private List<CardView> mViews;
    private List<SportsStopEntity.DataBean.SportMedalsBean> mData;
    private float mBaseElevation;
    private Context context;

    public CardPagerAdapter(Context context) {
        mData = new ArrayList<>();
        mViews = new ArrayList<>();
        this.context = context;
    }

    public void addCardItem(List<SportsStopEntity.DataBean.SportMedalsBean> item) {
        mViews.add(null);
        mData.addAll(item);
    }

    public float getBaseElevation() {
        return mBaseElevation;
    }

    @Override
    public CardView getCardViewAt(int position) {
        return mViews.get(position);
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View view = LayoutInflater.from(container.getContext())
                .inflate(R.layout.card_adapter, container, false);
        container.addView(view);
        bind(mData.get(position), view);
        CardView cardView = (CardView) view.findViewById(R.id.cardView);

        if (mBaseElevation == 0) {
            mBaseElevation = cardView.getCardElevation();
        }

        cardView.setMaxCardElevation(mBaseElevation * MAX_ELEVATION_FACTOR);
        mViews.set(position, cardView);
        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
        mViews.set(position, null);
    }

    private void bind(SportsStopEntity.DataBean.SportMedalsBean item, View view) {
        ImageView ivMedal = (ImageView) view.findViewById(R.id.iv_medal);
        TextView titleTextView = (TextView) view.findViewById(R.id.titleTextView);
        TextView tvMedal = (TextView) view.findViewById(R.id.tv_medal);
        titleTextView.setText(item.name);
        String str = "获得【%s】徽章";
        tvMedal.setText(String.format(str, item.name));
        tvMedal.setTextColor(Color.parseColor(item.color));
        titleTextView.setTextColor(Color.parseColor(item.color));
        GlideUtils.loadImage(context, item.url, ivMedal);
    }

}